<template>
    <div class="doc">
        <div class="delete-wrap">
            <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                size="tiny">
                <div >是否确认删除？</div>
                <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmDelete()">确 定</el-button>
                </span>
            </el-dialog>
        </div>
        <div class="share-page">
            <el-dialog
                title="分享文件"
                :visible.sync="shareVisible"
                size="small"
                show-close>
                <span v-for="item in currentFileNamePath">{{item}}/</span>
                <div class="text2">分享链接地址： </div>
                <div><el-input v-model="shareURL"></el-input></div>
                <div class="text-share">1.将生成的下载链接复制给好友</div>
                <div class="">2.默认分享的下载链接地址有效期48小时，过期后无效</div>
                <span slot="footer" class="dialog-footer">
                <el-button @click="shareVisible = false" class="closebtn">关 闭</el-button>
                </span>
            </el-dialog>
        </div>
        <div class="header clearfix">
            <h4 class="title">文档库<img src="../../assets/doc/doc.png"></h4>
            <span class="position" >现在位置：</span>
            <span class="position-list" v-for="item in currentFileNamePath">{{item}} /</span>
            <span class="button">
				<el-upload :action="actionPath" :data="dataId" :headers="authToken" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handlesuccess" :show-file-list="false">
			        <el-button size="small" type="primary"><i class="el-icon-upload2"></i></el-button>
			    </el-upload>
			</span>
            <span class="button" @click="addFolder()"><i class="el-icon-plus"></i></span>
			<span class="button" @click="backLastFolder()">返回</span>
        </div>
        <div class="table" v-loading="loading">
            <table>
                <tr>
                    <th>名称</th>
                    <th>大小</th>
                    <th>创建者</th>
                    <th>更新时间</th>
                </tr>
                <tr v-if="newFolder">
                    <td>
                        <img src="../../assets/doc/folder.png" class="newFolder-img">
                        <span class="new-folder"><input type="text" v-model="newFolderName"></span>
                        <span class="button"><button @click="defineAddFolder()">确认</button></span>
                        <span class="button"><button @click="cancelAddFolder()">取消</button></span> 
                    </td>
                    <td>-</td>
                    <td>-</td>
                    <td>-</td>
                </tr>
                <tr v-for="(item,index) in folderData">
                    <td class="cp">
                        <div class="folderName" @click="enterdoc(item.id, item.name, false)" :class="{hide: index == newDocIndex}">
                                <img src="../../assets/doc/folder.png" >{{ item.name }}
                        </div>
                        <div class="set-rename" :class="{show: index == newDocIndex}" >
                            <img src="../../assets/doc/folder.png">
                            <span class="new-folder"><input type="text" v-model="item.name"></span>
                            <span class="button"><button @click="ReDeAddFolder(item,index)">确认</button></span>
                            <span class="button"><button @click="ReCaAddFolder(index)">取消</button></span> 
                        </div>
                        <div class="icon-show" :class="{hide: index == newDocIndex}">
                            <div class="hover-show">
                               <!--  <i class="el-icon-share" @click="share(index,item)"></i>
                                <i class='el-icon-caret-bottom'></i> -->
                                <span class="set-pos">
                                    <i class="el-icon-more" @click="more(index,item)"></i>
                                    <div class="set-list" v-if="isSet" :class="{show:index == docIndex}">
                                        <div  @click="reName(index)">编辑</div>
                                        <div @click="deleteD()">删除</div>
                                        <!-- <div @click="share(index,item)">分享</div> -->
                                    </div>
                                </span>
                            </div>
                        </div>
                    </td>
                    <td>/</td>
                    <td>{{ item.createEmpName }}</td>
                    <td>{{ item.createTime }}</td>
                </tr>
                <tr v-for="(item,index) in fileData">
                    <td class="cp" >
                        <div class="folderName" @click="downloadFile(item.id)" :class="{hide: index == newFilIndex}">
                            <img src="../../assets/doc/file.png">{{ item.name }}
                        </div>
                        <div class="set-rename" :class="{show: index == newFilIndex}" >
                            <img src="../../assets/doc/file.png">
                            <span class="new-folder"><input type="text" v-model="item.name"></span>
                            <span class="button"><button @click="ReDeAddFile(item,index)">确认</button></span>
                            <span class="button"><button @click="ReCaAddFile(index)">取消</button></span> 
                        </div>
                        <div class="icon-show" :class="{hide: index == newFilIndex}">
                            <div class="hover-show">
                                <!-- <i class="el-icon-share" @click="share()"></i>
                                <i class='el-icon-caret-bottom' @click = "downloadFile(item.id)"></i> -->
                                <span class="set-pos">
                                    <i class="el-icon-more" @click="more(index,item)"></i>
                                    <div class="set-list" v-if="isSet" :class="{show:index == docIndex}">
                                        <div  @click="reFileName(index)">编辑</div>
                                        <div @click="deleteF()">删除</div>
                                        <div @click = "share(index,item)">分享</div>
                                        <div @click="downloadFile(item.id)">下载</div>
                                    </div>
                                </span>
                            </div>
                        </div>
                    </td>
                    <td>{{ item.size }}</td>
                    <td>{{ item.uploadEmpName }}</td>
                    <td>{{ item.uploadTime }}</td>
                </tr>
            </table>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                loading: false,
                newFolder: false,                
				newFolderName: '',
				newfileName: '',
                folderData: [],
                fileData: [],
                docIndex:null,
                newDocIndex:null,
                isSet:false,
                isRename:false,
                newFilIndex:null,
                dialogVisible:false,
                clickIndex:'',
                item:'',
                shareURL:'',
                shareVisible:false,
				authToken: { 'Xwt-Request-Token': localStorage.getItem('TOKEN') },
				actionPath: this.h +'/files/upload',
				dataId: {
					'projId': localStorage.getItem('projectId'),
					'directoryId': ""
				},
				currentFolderId:"",
				currentFilePath: [localStorage.getItem('projectId')],
				currentFileNamePath: [localStorage.getItem('projectName')],
                userId:'',
                role:localStorage.getItem('ROLE'),
                createProId:'',
                createDocId:''
			};        
		},
        methods: {
            handleRemove(file, fileData) {
				console.log(file, fileData);
			},
			handlePreview(file) {
				console.log(file);
			},
			handlesuccess(res) {
			    if(res.code == '200') {
                    console.log(res)
                    this.$message({
                        message: res.msg,
                        type: 'success'
                    });
                    var size = res.data.size;
                    if (size > 1024) {
                        if (size>1048576) {
                            if (size>1073741824) {
                                size = (size/1073741824).toFixed(2);
                                size = size+" GB";
                            }else{
                                size = (size/1048576).toFixed(2);
                                size = size+" MB";
                            }
                        }else{
                            size = (size/1024).toFixed(2);
                            size = size+" KB";
                        }
                    } else {
                        size = size+" B";
                    }
					this.fileData.push(
						{
							'uploadEmpName': res.data.uploadEmpName,
							'uploadTime': res.data.uploadTime,
							'size': size,
							'name': res.data.name,
                            'id': res.data.id,
                            'uploadEmpId':res.data.uploadEmpId
						}
					)
				} else {
                    this.$message.error(res.msg);
                }
			},            
            // 新建文件夹
            addFolder () {
                this.newFolder = true;
            },
            // 返回上一级文件夹
			backLastFolder () {
                if (this.currentFilePath.length<=1) {
                    return;
                }
				this.currentFilePath.splice(this.currentFilePath.length-1,1);
				this.currentFileNamePath.splice(this.currentFileNamePath.length-1,1);
				var currentParentId=this.currentFilePath[this.currentFilePath.length-1];
				var currentParentName=this.currentFileNamePath[this.currentFileNamePath.length-1];
				if(this.currentFilePath.length==1){
				    this.enterpro(currentParentId);
				}else{
					this.enterdoc(currentParentId,currentParentName,true);
				}
			},            
            // 取消新建
            cancelAddFolder () {
                this.newFolder = false;
            },
            deleteD() {
                this.dialogVisible = true;
                this.isSet = false;
            },
            deleteF() {
                this.dialogVisible = true;
                this.isSet = false;
            },
            // 分享
            share(index,item) {
                console.log(index,item)
                this.$http.post(
                    this.h + '/share' ,
                    {
                        "shareFileId": item.id, 
                        "shareEndTime": ""
                    },
                    {
                        headers: { 'Xwt-Request-Token': localStorage.getItem('TOKEN') },
                    }).then((res) => {
                        console.log(res)
                        this.shareURL = this.h + '/download/'+ res.data.data.id;
                        this.shareVisible = true;
                        this.isSet = false;
                    }).catch((err) => {
                        console.log("获取分享id失败！")
                    })
            },
            // 更多
            more(index,item) {
                console.log(index,item)
                if(item.createEmpId){
                    this.createDocId = item.createEmpId;
                }else {
                    this.createDocId = item.uploadEmpId;
                }
                this.createProId = localStorage.getItem('createEmpId');
                if(localStorage.getItem('ID') == this.createProId || localStorage.getItem('ID') == this.createDocId || this.role =='ADMIN') {
                    this.isSet = !this.isSet;
                    this.docIndex = index;
                }else {
                    this.isSet = false;
                }
                console.log(item)
                this.clickIndex = index;
                this.item = item;
                console.log("userId",localStorage.getItem('ID'))
                console.log(this.role,this.createProId,this.createDocId)
            },
            // 重命名
            reName(index) {
                this.isRename = true;
                this.newDocIndex = index;
                console.log(this.docIndex)
            },
            //删除文件
            deleteDoc(index) {
                this.$http.delete(
                    this.h + '/folders/' + this.folderData[index].id + '/projects/' + localStorage.getItem('projectId'),
                    {
                        headers: { 'Xwt-Request-Token': localStorage.getItem('TOKEN') }
                    }).then((res)=> {
                        console.log(res)
                        this.folderData.splice(index,1);
                        this.isSet = false;
                    }).catch((err) => {
                        console.log("删除文件夹未完成！")
                    })
            },
            // 确认新建
            defineAddFolder () {
				this.newFolder = false;
				this.$http.post(
						this.h + '/folders',
						{
							"name": this.newFolderName,
							"parentFolderId": this.currentFolderId,
							"projId": localStorage.getItem('projectId')
						},
						{
							headers: { 'Xwt-Request-Token': localStorage.getItem('TOKEN') }
						}
					)
					.then((res) => {
						if (res.data.code == '500') {
                            this.$alert(res.data.msg, '提示', {
                                type: 'error'
                            })
                        } else {
                            console.log(res)
                            this.folderData.push(res.data.data);
                        }
					})
					.catch((err) => {
						console.log(err);
					})
			},
            // 确认修改文件
            ReDeAddFolder(item,index) {
                console.log(this.folderData[index].id)
                this.$http.patch(
                    this.h + '/folders/' + this.folderData[index].id + '/projects/' + localStorage.getItem('projectId'),
                    {
                        'name':item.name
                    },
                    {
                        headers: { 'Xwt-Request-Token': localStorage.getItem('TOKEN') }
                    }).then((res) => {
                        console.log(res)
                        this.newDocIndex = null;
                        this.isSet = false;
                    }).catch((err)=> {
                        console.log('修改文件夹名称未完成！')
                    })
            },

            // 取消修改文件名称
            ReCaAddFolder() {
                this.newDocIndex = null;
                this.isSet = false;
                this.newFolderName = '';
            },
            // 修改文件夹名称
            editFolder() {
                this.newFolder = true;
            },
            // 修改文档名
            reFileName(index) {
                this.isRename = true;
                this.newFilIndex = index;
            },
            // 确认修改文档名
            ReDeAddFile(item,index) {
                console.log(item,index)
                console.log(this.fileData[index])
                this.$http.patch(
                    this.h+ '/files/' + this.fileData[index].id + '/projects/' + localStorage.getItem('projectId'),
                    {
                        "name":item.name
                    },
                    {
                        headers: { 'Xwt-Request-Token': localStorage.getItem('TOKEN') }
                    }).then((res)=> {
                        console.log(res)
                        this.newFilIndex =null,
                        this.isSet = false;
                        
                    }).catch((err) => {
                        console.log(err)
                    })
            },
            // 取消修改文档名
            ReCaAddFile(index) {
                this.newFilIndex = null;
                this.isSet = false;
            },
            // 删除文档
            deleteFile(index) {
                this.$http.delete(
                    this.h+ '/files/' + this.fileData[index].id + '/projects/' + localStorage.getItem('projectId'),
                    {
                        headers: { 'Xwt-Request-Token': localStorage.getItem('TOKEN') }
                    }).then((res)=> {
                        console.log(res)
                        this.fileData.splice(index,1) 
                    }).catch((err) => {
                        console.log(err)
                    })
            },
            // 确认删除
            confirmDelete() {
                if(this.item.createEmpId) {
                    this.deleteDoc(this.clickIndex) 
                }else {
                    this.deleteFile(this.clickIndex)
                }
                this.dialogVisible = false;
            },
			enterpro(id){
			    const proId=id;
				this.$http
					.get(
						this.h + '/projects/' + proId + '/files',
						{
							headers: { 'Xwt-Request-Token': localStorage.getItem('TOKEN') }
						}
					)
					.then((res) => {
						this.folderData =[];
						this.fileData =[];
						if (res.data.data.folder) {
							this.folderData = res.data.data.folder;
                            console.log(res)
						}
						if (res.data.data.file) {
                            var fileRes = res.data.data.file;
                            for (var i = 0; i < res.data.data.file.length; i++) {
                                if (fileRes[i].size > 1024) {
                                    if (fileRes[i].size>1048576) {
                                        if (fileRes[i].size>1073741824) {
                                            fileRes[i].size = (fileRes[i].size/1073741824).toFixed(2);
                                            fileRes[i].size = fileRes[i].size+" GB";
                                        }else{
                                            fileRes[i].size = (fileRes[i].size/1048576).toFixed(2);
                                            fileRes[i].size = fileRes[i].size+" MB";
                                        }
                                    }else{
                                        fileRes[i].size = (fileRes[i].size/1024).toFixed(2);
                                        fileRes[i].size = fileRes[i].size+" KB";
                                    }
                                }else{
                                    fileRes[i].size = fileRes[i].size+" B";
                                }
                            }
							this.fileData = res.data.data.file;
						}
						this.currentFolderId="";
						this.dataId.directoryId="";
					})
					.catch((err) => {
						console.log(err);
					});
			},
			//进入文件夹
			enterdoc (id, name, isBack) {
                console.log("进入")
                this.loading = true;
			    const folderId = id;
			    const folderName=name;
			    const isBackSign=isBack;
				this.$http
					.get(
						this.h + '/folders/' + folderId + '/files',
						{
							headers: { 'Xwt-Request-Token': localStorage.getItem('TOKEN') }
						}
					).then((res) => {
				        console.log(res);
                        this.loading = false;
						if (res.data.code == '200') {
							// this.$router.push({
							// 	path: '/doc',
							// 	query: {
							// 		'id': folderId
							// 	}
							// });
							// this.folderData = res.data.data.folder;
							this.folderData =[];
							this.fileData =[];
							if (res.data.data.folder) {
								this.folderData = res.data.data.folder;
							}
                            if (res.data.data.file) {
                                var fileRes = res.data.data.file;
                                for (var i = 0; i < res.data.data.file.length; i++) {
                                    if (fileRes[i].size > 1024) {
                                        if (fileRes[i].size>1048576) {
                                            if (fileRes[i].size>1073741824) {
                                                fileRes[i].size = (fileRes[i].size/1073741824).toFixed(2);
                                                fileRes[i].size = fileRes[i].size+" GB";
                                            }else{
                                                fileRes[i].size = (fileRes[i].size/1048576).toFixed(2);
                                                fileRes[i].size = fileRes[i].size+" MB";
                                            }
                                        }else{
                                            fileRes[i].size = (fileRes[i].size/1024).toFixed(2);
                                            fileRes[i].size = fileRes[i].size+" KB";
                                        }
                                    }else{
                                        fileRes[i].size = fileRes[i].size+" B";
                                    }
                                }
                                this.fileData = res.data.data.file;
                            }
							if(!isBackSign){
								this.currentFilePath.push(folderId);
								this.currentFileNamePath.push(folderName);
							}
							this.currentFolderId=folderId;
							this.dataId.directoryId=folderId;
						} else {
                            this.$alert('已经在根目录了！', '提示', {
                                type: 'error'
                            })
						};
				    })
			},
            // 下载文件
            downloadFile(id) {
                let fileId = id;
                this.$http.get(
                    this.h + '/files/' + fileId,
                    {
                        headers: { 'Xwt-Request-Token': localStorage.getItem('TOKEN') }
                    }).then((res) => {
                        location.href = this.h + '/files/getFile?pathId=' + encodeURIComponent(res.data.data);
                    })
            }
        },
        created() {
            var proId=localStorage.getItem('projectId');
            this.enterpro(proId);
        }
    };

</script>

<style lang="scss">
    .share-page .closebtn {
        width: 100px;
        height: 40px;
        background:#00C484;
        color: #fff;
        border-color: #00C484;
    }
    .share-page .closebtn:hover {
        background:#00C484;
        color: #fff;
    }
    .share-page .el-dialog__footer {
        text-align: center;
    }
    .text-share {
        margin : 20px 0 5px;
    }
    .text2 {
        margin: 10px 0px;
    }
    .newFolder-img {
        margin-right: 40px;
    }
    .cp {
        position: relative;
    }
    .icon-show {
        position: absolute;
        top: 0px;
        right: 0px;
        width: 100px;
        height: 100%;
    }
    .hover-show {
        display: none;
        height: 100%;
        line-height: 62px;
        text-align: right;
    }
    .cp:hover .hover-show{
        display: block;
    }
    .folderName {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
        padding: 15px 18px;
        box-sizing: border-box;
    }
    .set-pos {
        position: relative;
        // display: none;
    }
    .set-list {
        display: none;
        position: absolute;
        top: 20px;
        left: -21px;
        width: 60px;
        text-align: center;
        border: 1px solid #ccc;
        font-size: 12px;
        line-height: 25px;
        background: #fff;
        z-index: 20;
    }
    .set-rename {
        display: none;
    }
    .show {
        display: block;
    }
    .hide {
        display: none;
    }
    .doc .table table tr td .icon-show i{
        margin-right: 10px;
    }
    .share-page .el-dialog__header {
        text-align: center;
    }
    .share-page .el-dialog__title{
        height: 50px;
        font-size: 24px;
    }
    .doc {
        width: 92%;
        border-radius: 5px;
        margin: 34px 4%;
        border: 1px solid #e7e9f4;
        .header {
            width: 100%;
            z-index: 99;
            background: #f7f8fc;
            line-height: 56px;
            .title {
                float: left;
                margin-left: 42px;
                font-size: 16px;
                font-weight: bold;
                img {
                    vertical-align: middle;
                    margin-left: 5px;
                    margin-top: -2px;
                }
            }
            .position {
                margin-left: 40px;
            }
            .position-list {
                margin-left: 5px;
            }
            span {
                display: inline-block;
            }
            .button {
                width: 32px;
                height: 32px;
                border-radius: 16px;
                position: relative;
                float: right;
                font-size: 14px;
                color: #fff;
                background: #00c583;
                margin-right: 16px;
                margin-top: 13px;
                overflow: hidden;
                position: relative;
                text-align: center;
                line-height: 32px;
                cursor: pointer;
                input {
                    width: 100%;
                    position: absolute;
                    font-size: 10px;
                    left: 0;
                    top: 0;
                    opacity: 0;
                    filter: alpha(opacity=0);
                    cursor: pointer;
                }
                button {
                    line-height: 18px;
                }
                .el-button--primary {
                    background: #00c583;
                    border: 0!important;
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                }
            }
        }
        .table {
            width: 100%;
            table {
                width: 100%;
                font-size: 16px;
                color: #333;
                tr:first-child:hover {
                    background: #fff;
                }
                tr {
                    border-top: 1px solid #e7e9f4;
                }
                tr:hover {
                    background: #f6f6f6;
                    transition: .2s;
                }
                th {
                    color: #ccc;
                    font-size: 14px;
                    line-height: 32px;
                    text-align: center;
                    border-bottom: 1px solid #e7e9f4;
                }
                td {
                    line-height: 32px;
                    text-align: center;
                    padding: 15px 18px;
                    i {
                        margin-right: 40px;
                        color: #20a0ff;
                    }
                }
                img {
                    vertical-align: middle;
                }
                td:first-child {
                    text-align: left;
                    width: 45%;
                }
                .cp img {
                    margin-right: 40px;
                }
                .new-folder {
                    width: 200px;
                    display: inline-block;
                    margin-right: 30px;
                    input {
                        width: 100%;
                        border: 1px solid #d4d4d4;
                        border-radius: 5px;
                        height: 36px;
                        // margin-left: 35px;
                        font-size: 14px;
                        text-indent: 1rem;
                    }
                }
                .button {
                    display: inline-block;
                    button {
                        vertical-align: middle;
                        padding: 0 10px;
                        height: 36px;
                        font-size: 14px;
                        color: #fff;
                        background: #20a0ff;
                        border-radius: 3px;
                        border: none;
                        margin-left: 5px;
                    }
                }
            }
        }
    }
    
    
    

</style>